'use strict'
const db = uniCloud.database()
const _ = db.command
const MAX_LIMIT = 20
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  try {
    let body = event
    if (event.body) {
      body = JSON.parse(event.body) // 兼容 Apifox 传入 JSON 字符串
    }

    const {
      uniIdToken,
      page = 1,
      pageSize = MAX_LIMIT
    } = body

    const uniIDIns = uniID.createInstance({ context })
    const tokenRes = await uniIDIns.checkToken(uniIdToken)

    if (tokenRes.code !== 0) {
      return {
        success: false,
        message: '身份验证失败'
      }
    }

    const consultantId = tokenRes.uid

    // 1. 查询当前咨询师的记录
    const matchCondition = { consultant: consultantId }

    const res = await db.collection('appoint_records')
      .where(matchCondition)
      .orderBy('create_time', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()

    const totalRes = await db.collection('appoint_records')
      .where(matchCondition)
      .count()

    const records = res.data
    const uidList = [...new Set(records.map(r => r.user))]

    // 2. 查询用户昵称
    const userRes = await db.collection('uni-id-users')
      .where({ _id: _.in(uidList) })
      .field({ _id: true, nickname: true })
      .get()

    const userMap = {}
    userRes.data.forEach(user => {
      userMap[user._id] = user.nickname || '未知用户'
    })

    // 3. 查询咨询师姓名
    const consultantRes = await db.collection('consultants')
      .where({ user_id: consultantId })
      .field({ user_id: true, name: true })
      .get()

    const consultantName = consultantRes.data[0]?.name || '未知咨询师'

    // 4. 合并数据
    const finalData = records.map(item => ({
      ...item,
      userNickname: userMap[item.user] || '未知用户',
      consultantName
    }))

    return {
      success: true,
      result: {
        total: totalRes.total,
        page,
        pageSize,
        data: finalData
      }
    }

  } catch (err) {
    console.error('获取咨询师记录失败:', err)
    return {
      success: false,
      message: '查询失败',
      error: err.message
    }
  }
}
